package com.interest.controller;

import com.interest.controller.builder.ErrorModelAndViewBuilder;
import com.interest.modules.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * 登陆控制器
 *
 * @author wangliang
 */
@Controller
public class LoginController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView login(@RequestParam(value = "username", required = true) String username,
                              @RequestParam(value = "password", required = true) String password, HttpSession session) {
        if (username == null || username.length() == 0) {
            return new ErrorModelAndViewBuilder("用户名为空").build();
        } else if (password == null || password.length() == 0) {
            return new ErrorModelAndViewBuilder("密码为空").build();
        } else {
            int uid = accountService.login(username, password);
            if (uid > 0) {
                session.setAttribute("account", username);
                return new ModelAndView("redirect:/github/trending/list");
            } else {
                return new ErrorModelAndViewBuilder("用户名密码错误").build();
            }
        }
    }
}
